import Vue from 'vue'
import Vuex from 'vuex'
import $router from '@/router/'
import { routeArr1 } from '@/const/menu.js'


const getRoutes = (routeArr = []) => {
    var arr = []
    routeArr.forEach(r => {
        arr.push({
            path: r.link,
            // name: r.link.replace(/\//g, '-'), //  路由中的/替换为-作为name
            name: r.title,
            component: () => import('@/views' + r.link),        //会默认将这些路由文件 prefetch，并且将需要的文件 preload
            //有子路由则重定向至第一个子路由
            redirect: r.children && r.children.length ? r.children[0].link : null,     //递归获取子路由
            children: r.children && r.children.length ? getRoutes(r.children) : null
        })
    })
    return arr
}


Vue.use(Vuex)



export default new Vuex.Store({
    state: {
        menus: [],
        currTitle: '',
        username: sessionStorage.getItem('username') || ''
    },
    mutations: {
        setMenu(state, payload) {
            state.menus = payload
        },
        setTitle(state, payload) {
            state.currTitle = payload
        },
        setUserName(state, payload) {
            state.username = payload
        }
    },
    actions: {
        getMenu({ commit }, payload) {
            const route = getRoutes(routeArr1)
            commit('setMenu', routeArr1)
            commit('setTitle', '测试')
            $router.addRoutes([
                {
                    path: '/',
                    component: () => import('@/views/pages/index'),
                    children: route
                },
                {
                    path: '*',
                    redirect: '/login'
                }
            ])
            return Promise.resolve(route[0].path)
        }
    }
})
